package cn.fan.service;

import cn.fan.feign.clients.UserClient;
import cn.fan.feign.pojo.FundData;
import cn.fan.feign.pojo.FundMain;
import cn.fan.feign.pojo.User;
import cn.fan.mapper.EmailRecordMapper;
import cn.fan.mapper.TaskRemindMapper;
import cn.fan.pojo.EmailRecord;
import cn.fan.pojo.TaskRemind;
import cn.fan.rabbitMQ.snnd.EmailMQSend;
import cn.fan.redis.MSGRedis;
import cn.fan.pojo.MyMail;
import cn.fan.utils.R;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class EmailRecordService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private EmailMQSend emailMQ;

    @Autowired
    private EmailRecordMapper emailRecordMapper;

    @Autowired
    private TaskRemindMapper taskRemindMapper;

    @Autowired
    private MSGRedis msgRedis;

    public boolean sendEmail(TaskRemind remind, FundData newFundData, FundMain fundMain){
        try {
            Date date=new Date();

            EmailRecord emailRecord=new EmailRecord();
            String theme;

            String fundName=fundMain.getFundname();
            String fundCode=fundMain.getCode();
            if(remind.getUpdownFlag()==0)
                theme="【买入通知】"+fundName+"("+fundCode+")";
            else
                theme="【卖出通知】"+fundName+"("+fundCode+")";
            emailRecord.setMailTheme(theme);

            String addressee = getAddressee(remind);
            if ("".equals(addressee))
                return false;

            emailRecord.setAddressee(addressee);
            String content=getContent(newFundData,remind,fundName);
            emailRecord.setMailContent(content);
            emailRecord.setUserid(remind.getCreateBy());
            emailRecord.setCreateDate(date);
            // 发送邮件→通过mq 先存redis，然后通知
            sendMail(emailRecord);
            emailRecordMapper.insert(emailRecord);

            if(emailRecord.getIssuccess()==1){
                remind.setIsnotice(1);
                remind.setUpdateDate(date);
                remind.setEmailId(emailRecord.getId());
                taskRemindMapper.updateById(remind);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private String getAddressee(TaskRemind remind){
        R r = userClient.get(remind.getCreateBy());
        if( !"0".equals(r.get("code").toString()) || r.get("user")==null )
            return "";
        String userStr= JSON.toJSONString(r.get("user"));
        User user= JSONObject.parseObject(userStr,User.class);
        if(user==null)
            return "";
        else
            return user.getEmailadd();
    }

    private String getContent(FundData fundData,TaskRemind taskRemind,String indexName){
        String content="基金【"+indexName+"】单位净值已";
        if(taskRemind.getUpdownFlag()==0)
            content+="跌至("+fundData.getNetworth()+")，" +"等于或低于预期值："+taskRemind.getDwjz()+",当前可进行买入！\n" ;
        else if(taskRemind.getUpdownFlag()==1)
            content+="涨至("+fundData.getNetworth()+")，" +"等于或高预期值："+taskRemind.getDwjz()+",当前可进行卖出！\n" ;

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");

        String updownflag= taskRemind.getUpdownFlag()==0?"跌":"涨";

        content+="\n详细信息如下：" +
                "\n  当前基金信息：" +
                "\n    基金代码：" +fundData.getCode()+
                "\n      基金名称：" +indexName+
                "\n      截止日期：" +fundData.getFunddate()+
                "\n      单位净值：" +fundData.getNetworth()+
                "\n      创建时间：" +sdf.format(fundData.getCreateDate())+
                "\n"+
                "\n    任务提醒信息：" +
                "\n      涨跌标志：" +updownflag+
                "\n      单位净值：" +taskRemind.getDwjz()+
                "\n      创建时间：" +sdf.format(taskRemind.getCreateDate())+
                "\n";
        return content;
    }

    public void sendMail(EmailRecord emailRecord){
        try {
            Integer uuid=UUID.randomUUID().toString().replaceAll("-","").hashCode();
            long myMailId=uuid;
            MyMail myMail=new MyMail(myMailId,emailRecord.getAddressee(), emailRecord.getMailTheme(), emailRecord.getMailContent());
            msgRedis.putMail(myMailId,myMail);

            emailMQ.sendEmail(myMailId);

            emailRecord.setIssuccess(1);
        }catch (Exception e){
            emailRecord.setIssuccess(0);
            emailRecord.setFailureCause(e.toString().substring(0,299));
        }

    }

}
